<template>
  <NuxtLayout name="admin" menuActive="/admin/student">
    <div class="card">
      <el-page-header @back="useRouter().go(-1)">
        <template #content>
          <el-input v-model="listForm.keyword" placeholder="请输入学员名称">
            <template #append>
              <el-button :icon="Search" @click="searchFn"></el-button>
            </template>
          </el-input>
        </template>
        <template #extra>
          <div class="flex items-center">
            <el-button @click="addFn">添加学员</el-button>
          </div>
        </template>
      </el-page-header>
      <div style="height: 18px;"></div>
      <el-table :data="tableData" border >
        <el-table-column prop="name" label="学员姓名" width="90" />
        <el-table-column prop="phoneNo" label="手机号码" width="120" />
        <el-table-column label="身份证人像面" width="130">
          <template #default="scope">
            <el-image v-show="scope.row.idFrontImg" :src="scope.row.idFrontImg" :preview-src-list="[scope.row.idFrontImg]" fit="cover" preview-teleported lazy style="width: 100px;height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column label="身份证国徽面" width="130">
          <template #default="scope">
            <el-image v-show="scope.row.idBackImg" :src="scope.row.idBackImg" :preview-src-list="[scope.row.idBackImg]" fit="cover" preview-teleported lazy style="width: 100px;height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column label="健康证明" width="130">
          <template #default="scope">
            <el-image v-show="scope.row.medicalCert" :src="scope.row.medicalCert" :preview-src-list="[scope.row.medicalCert]" fit="cover" preview-teleported lazy style="width: 100px;height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column label="学历证明" width="130">
          <template #default="scope">
            <el-image v-show="scope.row.diplomaCert" :src="scope.row.diplomaCert" :preview-src-list="[scope.row.diplomaCert]" fit="cover" preview-teleported lazy style="width: 100px;height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column label="大头证件照" width="130">
          <template #default="scope">
            <el-image v-show="scope.row.headShot" :src="scope.row.headShot" :preview-src-list="[scope.row.headShot]" fit="cover" preview-teleported lazy style="width: 100px;height: 100px;" />
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="学员加入时间" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="270">
          <template #default="scope">
            <a class="el-button el-button--info el-button--small" :href="`/admin/learning/${useRoute().params.id}/${scope.row.id}`">学习记录</a>
            <a class="el-button el-button--warning el-button--small" :href="`/admin/exam/${useRoute().params.id}/${scope.row.id}`">考试记录</a>
            <el-button type="primary" size="small" @click="certificateFn(scope.row)">颁发证书</el-button>
            <a class="el-button el-button--small" :href="`/admin/certificate/user-${scope.row.userId}.html`">查看证书</a>
            <el-button type="success" size="small" @click="editFn(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="delFn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card_pagin">
        <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="listForm.pageSize"
          @change="pageChangeFn" />
      </div>
    </div>
    <MyForm :visible="formVisible" :forms="forms" :title="formTitle" @pick="formPickFn" />
    <MyFormCertificate :visible="formCertificateVisible" :forms="formsCertificate" title="颁发证书" @pick="formsCertificatePickFn" />
  </NuxtLayout>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { classesUserPageList, addClassesUser, updateClassesUser, deleteClassesUser, addCertificate } from '~/server/api';
import { formatTime } from '~/utils/utils';
import MyForm from './form'
import MyFormCertificate from './form_certificate'
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
useSeoMeta({
  title: "技考邦_学员管理",
  keywords: "技考邦,学员管理",
  description: "技考邦，学员管理。",
  ogTitle: "技考邦_学员管理",
  ogDescription: "技考邦，学员管理。",
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
// 列表
const listForm = ref({
  pageNum: 1,
  pageSize: 20,
  classesId: useRoute().params.id,
  keyword: ''
})
const tableData = ref([])
const total = ref(0)
const getList = async () => {
  let { data: listRes } = await useAsyncData('classesUserPageList', () => useServerRequest(classesUserPageList, {
    method: 'post',
    body: JSON.stringify(listForm.value)
  }))
  if (listRes.value && listRes.value.errno === 0 && listRes.value.result) {
    tableData.value = listRes.value.result.list;
    total.value = listRes.value.result.total;
  }
}
getList()
// 搜索
const searchFn = () => {
  listForm.value.pageNum = 1;
  getList()
}
// 分页
const pageChangeFn = (val) => {
  listForm.value.pageNum = val;
  getList()
}
// 添加
const forms = ref({})
const formVisible = ref(false)
const formTitle = ref('')
const addFn = () => {
  forms.value.id = null;
  forms.value.phoneNo = '';
  forms.value.name = '';
  forms.value.idFrontImg = '';
  forms.value.idFrontImgStatus = 0;
  forms.value.idBackImg = '';
  forms.value.idBackImgStatus = 0;
  forms.value.medicalCert = '';
  forms.value.medicalCertStatus = 0;
  forms.value.diplomaCert = '';
  forms.value.diplomaCertStatus = 0;
  forms.value.headShot = '';
  forms.value.headShotStatus = 0;
  forms.value.classesId = useRoute().params.id;
  formTitle.value = '添加学员';
  formVisible.value = true;
}
// 编辑
const editFn = (val) => {
  forms.value.id = val.id;
  forms.value.phoneNo = val.phoneNo;
  forms.value.name = val.name;
  forms.value.idFrontImg = val.idFrontImg;
  forms.value.idFrontImgStatus = val.idFrontImgStatus || val.idFrontImg ? 2 : 0;
  forms.value.idBackImg = val.idBackImg;
  forms.value.idBackImgStatus = val.idBackImgStatus || val.idBackImg ? 2 : 0;
  forms.value.medicalCert = val.medicalCert;
  forms.value.medicalCertStatus = val.medicalCertStatus || val.medicalCert ? 2 : 0;
  forms.value.diplomaCert = val.diplomaCert;
  forms.value.diplomaCertStatus = val.diplomaCertStatus || val.diplomaCert ? 2 : 0;
  forms.value.headShot = val.headShot;
  forms.value.headShotStatus = val.headShotStatus || val.headShot ? 2 : 0;
  forms.value.classesId = useRoute().params.id;
  formTitle.value = '编辑学员';
  formVisible.value = true;
}
// 删除
const delFn = (val) => {
  ElMessageBox.confirm('是否删除当前数据', {
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    let delRes = await useServerRequest(deleteClassesUser, {
      method: 'post',
      body: JSON.stringify({
        classesId: useRoute().params.id,
        id: val.id
      })
    })
    if (delRes.errno === 0) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getList()
      return false;
    }
  }).catch(() => {})
}
// 取消 确认
const formPickFn = async (e) => {
  if (e.form) {
    if (e.form.name == '') {
      ElMessage({
        message: '学员姓名有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (!/^1[3456789]\d{9}$/.test(e.form.phoneNo)) {
      ElMessage({
        message: '手机号码有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    const loading = ElLoading.service({ text: '请求中...', target: document.querySelector('.el-dialog') })
    let url = e.form.id ? updateClassesUser : addClassesUser;
    let classRes = await useServerRequest(url, {
      method: 'post',
      body: JSON.stringify(e.form)
    })
    if (classRes.errno === 0) {
      ElMessage({
        message: e.form.id ? '修改成功' : '添加成功',
        type: 'success'
      })
      getList()
      formVisible.value = e.visible;
    }
    loading.close()
    return false;
  }
  formVisible.value = e.visible;
}
// 颁发证书
const formCertificateVisible = ref(false)
const formsCertificate = ref({
  type: '理论',
  name: '',
  idNumber: '',
  subject: '',
  address: '',
  startTime: '',
  endTime: '',
  hours: 0,
  stampImg: '',
  signImg: '',
  pubdate: formatTime(new Date().getTime(), 'Y-m-d'),
  classesId: null,
  userId: null
})
const certificateFn = (val) => {
  let mechanism = useRoute().meta.mechanism;
  formsCertificate.value.name = val.name;
  formsCertificate.value.address = mechanism.address;
  formsCertificate.value.stampImg = mechanism.stampImg;
  formsCertificate.value.signImg = mechanism.signImg;
  formsCertificate.value.classesId = val.classesId;
  formsCertificate.value.userId = val.userId;
  formCertificateVisible.value = true;
}
const formsCertificatePickFn = async (e) => {
  if (e.form) {
    if (e.form.type == '') {
      ElMessage({
        message: '请选择证书类型',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.name == '') {
      ElMessage({
        message: '学员姓名有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (!/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/.test(e.form.idNumber)) {
      ElMessage({
        message: '身份证号有误',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.subject == '') {
      ElMessage({
        message: '请输入培训工种',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.address == '') {
      ElMessage({
        message: '请输入培训地点',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.startTime == '') {
      ElMessage({
        message: '请选择培训开始时间',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.endTime == '') {
      ElMessage({
        message: '请选择培训结束时间',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.hours == '') {
      ElMessage({
        message: '请输入培训学时',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.stampImg == '') {
      ElMessage({
        message: '请上传印章图片',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.signImg == '') {
      ElMessage({
        message: '请上传签名图片',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    if (e.form.pubdate == '') {
      ElMessage({
        message: '请选择发证时间',
        type: 'warning',
        appendTo: document.querySelector('.el-dialog') || document.body
      })
      return false
    }
    const loading = ElLoading.service({ text: '请求中...', target: document.querySelector('.el-dialog') })
    let res = await useServerRequest(addCertificate, {
      method: 'post',
      body: JSON.stringify(e.form)
    })
    if (res && res.errno === 0) {
      ElMessage.success('颁发成功')
      getList()
      formCertificateVisible.value = e.visible;
    }
    loading.close()
    return false;
  }
  formCertificateVisible.value = e.visible;
}
</script>

<style lang="less" scoped>
.card {
  background: #FFFFFF;
  border-radius: 10px;
  border: 1px solid #EEEEEE;
  padding: 35px 25px;

  &_pagin {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
}
</style>